package com.order.service;

import com.order.entity.SysUser;
import com.order.mapper.SysUserMapper;
import com.order.mapper.OrderInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务
 */
@Service
public class UserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 根据ID获取用户
     */
    public SysUser getUserById(Long id) {
        return sysUserMapper.findById(id);
    }

    /**
     * 获取技术员列表
     */
    public List<SysUser> getTechList() {
        return sysUserMapper.findByRoleType(4);
    }

    /**
     * 更新用户信息
     */
    public void updateUserInfo(SysUser user) {
        sysUserMapper.update(user);
    }

    /**
     * 获取用户统计信息
     */
    public Map<String, Object> getUserStats(Long userId, Integer roleType) {
        Map<String, Object> stats = new HashMap<>();
        
        if (roleType == 3) { // 用户
            List<com.order.entity.OrderInfo> userOrders = orderInfoMapper.selectByUserId(userId);
            stats.put("totalOrders", userOrders.size());
            stats.put("completedOrders", userOrders.stream().mapToInt(o -> o.getStatus() == 4 ? 1 : 0).sum());
            stats.put("processingOrders", userOrders.stream().mapToInt(o -> o.getStatus() == 2 ? 1 : 0).sum());
        } else if (roleType == 4) { // 技术员
            List<com.order.entity.OrderInfo> techOrders = orderInfoMapper.selectByTechId(userId);
            stats.put("totalOrders", techOrders.size());
            stats.put("completedOrders", techOrders.stream().mapToInt(o -> o.getStatus() == 4 ? 1 : 0).sum());
            stats.put("processingOrders", techOrders.stream().mapToInt(o -> o.getStatus() == 2 ? 1 : 0).sum());
            
            // 计算总收入
            double totalEarnings = techOrders.stream()
                .filter(o -> o.getStatus() == 4)
                .mapToDouble(o -> o.getBudget().doubleValue())
                .sum();
            stats.put("totalEarnings", totalEarnings);
        }
        
        return stats;
    }

    /**
     * 分页查询用户列表
     */
    public List<SysUser> getUserList(Integer offset, Integer pageSize, String keyword, Integer roleType) {
        return sysUserMapper.findPage(offset, pageSize, keyword, roleType);
    }

    /**
     * 统计用户数量
     */
    public Long countUsers(String keyword, Integer roleType) {
        return sysUserMapper.countUsers(keyword, roleType);
    }

    /**
     * 更新用户状态
     */
    public void updateUserStatus(Long userId, Integer status) {
        SysUser user = sysUserMapper.findById(userId);
        if (user != null) {
            user.setStatus(status);
            sysUserMapper.update(user);
        }
    }
}